// ./mongodb/manager/user/userManager.js
const { UserModel: User } = require("../../entity");
const bcrypt = require("bcrypt");

class UserManager {
  // 创建用户
  static async createUser({ email, username, password, role = "user" }) {
    const hashedPassword = await bcrypt.hash(password, 10); // 加密密码
    const user = new User({ email, username, password: hashedPassword, role }); // 创建用户
    return await user.save();
  }

  // 更新用户
  static async updateUser(userId, updateData) {
    // 如果有更新密码，重新加密
    if (updateData.password) {
      updateData.password = await bcrypt.hash(updateData.password, 10);
    }
    return await User.findByIdAndUpdate(userId, updateData, {
      new: true,
    }).exec(); // 设置 new 为 true 就返回更新后的文档(没有就是更新前的)
  }

  // 删除用户(标记删除)
  static async softDeleteUser(userId) {
    return await User.findByIdAndUpdate(
      userId,
      { deleted: true },
      { new: true },
    ).exec();
  }

  // 删除用户(永久删除)
  static async deleteUser(userId) {
    return await User.findByIdAndDelete(userId).exec();
  }

  // 查找用户(根据用户 ID)
  static async getUserById(userId) {
    const user = await User.findById(userId).exec();
    if (!user || user.deleted) {
      throw new Error("User not found or deleted");
    }
    return user;
  }

  // 查找用户(根据用户 Email)
  static async getUserByEmail(email) {
    const user = await User.findOne({ email, deleted: false }).exec();
    if (!user) {
      throw new Error("User not found");
    }
    return user;
  }

  // 查找用户(根据用户昵称)
  static async getUserByUsername(username) {
    const user = await User.findOne({ username, deleted: false }).exec();
    if (!user) {
      throw new Error("User not found");
    }
    return user;
  }

  // 查找用户(获取所有未删除用户)
  static async getAllActiveUsers() {
    return await User.find({ deleted: false }).exec();
  }

  // 验证用户(电子邮件和密码验证)
  static async validateUser(email, password) {
    const user = await this.getUserByEmail(email); // 使用已有的 getUserByEmail 函数获取用户
    const passwordMatch = await bcrypt.compare(password, user.password); // 验证密码

    if (!passwordMatch) {
      return null; // 密码不匹配时返回 null
    }

    // 密码匹配，返回用户信息（去掉密码）
    const { password: _, ...userWithoutPassword } = user.toObject(); // 使用 toObject() 去掉密码
    return userWithoutPassword;
  }
}

module.exports = UserManager;
